import { defineStore } from 'pinia';

export const useTabsStore = defineStore('tabs', {
    state: () => ({
        tabs: [
            { path: '/homePage', meta: { title: '首页' }, closable: false },
        ], // 存储导航标签的数组
        userData: '11111',
        activeTab: '',
        messageID: ''
    }),
    // 在添加/删除标签时更新本地存储
    actions: {
        initializeFromLocalStorage ()
        {
            // 从本地存储加载数据并恢复状态
            const savedTabs = JSON.parse(localStorage.getItem('tabs')) || [];
            if (Array.isArray(savedTabs) && savedTabs.length > 0) {
                this.tabs = savedTabs;
            }
        },

        addActiveTab (path)
        {
            // 改变状态
            this.activeTab = path;
        },
        addTab (tab)
        {
            this.tabs.push(tab);
            this.writeToLocalStorage(); // 将数据写入本地存储
        },
        writeToLocalStorage ()
        {
            localStorage.setItem('tabs', JSON.stringify(this.tabs));
        },
        removeTab (index)
        {
            console.log('removeTab', index);
            this.tabs.splice(index, 1);
            console.log(this.tabs, "标签数组");
            localStorage.setItem('tabs', JSON.stringify(this.tabs));
        },
        // 关闭所有标签页面
        removeAllTab ()
        {
            this.tabs = [
                { path: '/homePage', meta: { title: '首页' }, closable: false },
            ]
            this.activeTab = '/homePage'
            localStorage.setItem('tabs', JSON.stringify(this.tabs));
        },
        // 存储当前登入的信息
        setUserData (userData)
        {
            this.userData = userData;
            localStorage.setItem('userData', JSON.stringify(userData));
        },
        // 读取当前登入的信息
        getUserData ()
        {
            const storedUserData = localStorage.getItem('userData');
            return storedUserData ? JSON.parse(storedUserData) : null;
        },
        setMessageID (messageID)
        {
            this.messageID = messageID
            localStorage.setItem('messageID', this.messageID);
        },
        getMessageID ()
        {
            return this.messageID
        }
    }
});
